package org.dydl.common.util;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import org.springframework.http.ResponseEntity;

/**
 * 压缩文件
 * 
 * @Description:
 * @author DWL
 * @date 2016年7月27日 下午2:05:32
 * @version V1.0
 */
public class ZipUtils extends ExportToFile{
	public static ResponseEntity<byte[]> createZipFile(List<ByteArrayOutputStream> outputStreamList, String zipFileName, String downloadToken)
			throws IOException {
		try {
			byte[] buffer = new byte[1024];
			ByteArrayOutputStream bos = new ByteArrayOutputStream();
			ZipOutputStream zipOutputStream = new ZipOutputStream(bos);
			// 日期格式化
			SimpleDateFormat sdf = new SimpleDateFormat("yyMMddHHmmss");
			// 得到当前指定格式的日期
			String now = sdf.format(new Date());
			int i = 0;
			for (ByteArrayOutputStream byteArrayOutputStream : outputStreamList) {
				String fileName = String.format("%s_%s.xml", zipFileName, now + i) ;
				File fileTemp = File.createTempFile(fileName, ".xml");
//				fileTemp.deleteOnExit();
				FileOutputStream fileOutputStream = new FileOutputStream(fileTemp);
				fileOutputStream.write(byteArrayOutputStream.toByteArray());
				
				ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(
						byteArrayOutputStream.toByteArray());
				int bytesRead = 0;
				
				zipOutputStream.putNextEntry(new ZipEntry(fileName));
				while ((bytesRead = byteArrayInputStream.read(buffer)) != -1) {
					zipOutputStream.write(buffer, 0, bytesRead);
				}
				zipOutputStream.closeEntry();
				
				fileOutputStream.flush();
				fileOutputStream.close();
				bos.close();
				byteArrayInputStream.close();
				// 删除临时文件
				fileTemp.delete();
				i++;
			}
			zipOutputStream.close();
			return export2File(zipFileName + ".zip", downloadToken, bos);
		} catch (IOException e) {
			e.printStackTrace();
			throw new IOException("error");
		} finally {
		}
	}
}
